import { Stack, useLocalSearchParams } from "expo-router";
import { Platform, Text, View } from "react-native";
import { WebView } from "react-native-webview";

export default function MapScreen() {
  const params = useLocalSearchParams<{
    lat?: string;
    lon?: string;
    name?: string;
    headImg?: string;
  }>();

  // 参数解析
  const latitude = params.lat ? Number(params.lat) : 22.54286;
  const longitude = params.lon ? Number(params.lon) : 114.05956;
  const label = params.name || "未知位置";

  // 头像/Marker 图片（可替换为你的 OSS 链接）
  const avatar =
    params.headImg ||
    "https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/markerDefault.png";

  // 注意：请使用你自己的 KEY
  const TENCENT_MAP_KEY = "NP2BZ-RPWK6-P4QSL-MF4N5-KVGIV-4KBEZ";

  // -------- 核心修复点 --------
  // 1) MultiMarker 的 styles 需使用 new TMap.MarkerStyle({ src, width, height, anchor, ... })
  // 2) 文本标注使用 MultiLabel（GL JS 没有 TMap.Text，不能 map.addControl(label)）
  const html = `
    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8" />
        <meta
          name="viewport"
          content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"
        />
        <style>
          html, body { margin: 0; padding: 0; height: 100%; background: #f5f5f5; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Arial; }
          .container { display: flex; flex-direction: column; align-items: center; height: 100vh; }
          .coord { font-size: 14px; color: #666; margin: 6px 0 0; }
          #map { width: 94vw; height: 68vh; margin-top: 8px; border-radius: 12px; overflow: hidden; background: #fff; }
        </style>
        <script>
          (function () {
            try {
              var t='__t__'; localStorage.setItem(t,'1'); localStorage.removeItem(t);
            } catch (e) {
              var store={};
              window.localStorage = {
                getItem:k=>Object.prototype.hasOwnProperty.call(store,k)?store[k]:null,
                setItem:(k,v)=>{store[k]=String(v)},
                removeItem:k=>{delete store[k]},
                clear:()=>{store={}},
                key:i=>Object.keys(store)[i]||null,
                get length(){return Object.keys(store).length}
              };
            }
          })();
        </script>
        <script src="https://map.qq.com/api/gljs?v=1.exp&key=${TENCENT_MAP_KEY}"></script>
      </head>
      <body>
        <div class="container">
          <div class="coord">名称：${label.replace(/</g,"&lt;").replace(/>/g,"&gt;")}</div>
          <div class="coord">纬度：${latitude}　经度：${longitude}</div>
          <div id="map"></div>
        </div>
        <script>
          function init() {
            try {
              if (typeof TMap === "undefined" || !TMap.Map) {
                document.getElementById("map").innerHTML =
                  '<div style="color:red;text-align:center;padding:20px;">地图加载失败：TMap 未定义（请检查 KEY 或网络）</div>';
                return;
              }

              var center = new TMap.LatLng(${latitude}, ${longitude});
              var map = new TMap.Map("map", {
                center: center,
                zoom: 15,
                pitch: 0,
                rotation: 0
              });

              // ---- 点标记：正确的样式写法 ----
              var markerLayer = new TMap.MultiMarker({
                map: map,
                styles: {
                  avatarStyle: new TMap.MarkerStyle({
                    width: 40,
                    height: 40,
                    // 锚点（像素）：让“针尖/底部中心”对准坐标
                    anchor: { x: 20, y: 40 },
                    // 关键：图片地址字段是 src（不是 face）
                    src: "${avatar}"
                  })
                },
                geometries: [{
                  id: "marker",
                  styleId: "avatarStyle",
                  position: center,
                  properties: { title: "${label.replace(/"/g, '\\"')}" }
                }]

                });

              // ---- 文本标注：使用 MultiLabel，而非 TMap.Text ----
              var labelLayer = new TMap.MultiLabel({
                map: map,
                styles: {
                  labelStyle: new TMap.LabelStyle({
                    color: "#333",
                    size: 16,
                    // 文本描边，提升可读性
                    strokeColor: "#fff",
                    strokeWidth: 2,
                    // 文本位置/偏移（相对坐标点）
                    direction: "center",
                    offset: { x: 0, y: -48 }
                  })
                },
                geometries: [{
                  id: "label",
                  styleId: "labelStyle",
                  position: center,
                  content: "${label.replace(/"/g, '\\"')}"
                }]
              });

              // 视野微调，确保标记与文字都在视口舒适区（可选）
              map.setCenter(center);
            } catch (e) {
              document.getElementById("map").innerHTML =
                '<div style="color:red;text-align:center;padding:20px;">初始化异常：' + (e && e.message ? e.message : e) + '</div>';
            }
          }

          if (document.readyState === "complete") {
            init();
          } else {
            window.addEventListener("load", init);
          }
        </script>
      </body>
    </html>
  `;

  return (
    <View style={{ flex: 1 }}>
      <Stack.Screen
        options={{ title: `${label}的位置`, headerBackTitle: "返回" }}
      />
      <WebView
        originWhitelist={["*"]}
        source={{ html, baseUrl: "https://map.qq.com/" }}
        style={{ flex: 1 }}
        javaScriptEnabled
        domStorageEnabled
        startInLoadingState
        // Android 如需加载 http 资源，可放开下面一行（你目前用的是 https，不必开启）
        mixedContentMode={Platform.OS === "android" ? "always" : "never"}
        renderError={(errorName) => (
          <View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
            <Text>WebView 加载失败: {String(errorName)}</Text>
          </View>
        )}
      />
    </View>
  );
}
